<template>
  <ElInput v-model="value">
    <template #append>
      <ElPopover trigger="click" width="390px" placement="bottom-end">
        <ElScrollbar>
          <div style="width: calc(100% - 30px); padding: 0 10px">
            <ElInput v-model="iconName" placeholder="搜索图标"></ElInput>
          </div>
          <ul class="icon-list">
            <li
              :class="['icon-item', { active: value === icon }]"
              v-for="icon in getIcons"
              :key="icon"
              @click="selectedIcon(icon)"
            >
              <ElButton link>
                <ElIcon>
                  <Icon :icon="icon"></Icon>
                </ElIcon>
              </ElButton>
            </li>
          </ul>
          <ElPagination
            layout="prev, pager, next"
            :total="total"
            v-model:page-size="pageSize"
            v-model:current-page="currentPage"
          />
        </ElScrollbar>
        <template #reference>
          <ElButton link>
            <ElIcon>
              <Icon :icon="value"></Icon>
            </ElIcon>
          </ElButton>
        </template>
      </ElPopover>
    </template>
  </ElInput>
</template>

<script setup lang="ts" name="IconPicker">
import { ElInput, ElPopover, ElScrollbar, ElPagination, ElButton, ElIcon } from "element-plus";
import Icon from "./Icon.vue";
import icons from "./icons";
import { computed, ref } from "vue";
const props = defineProps({
  modelValue: {
    type: String
  }
});
const value = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emit("update:modelValue", val);
  }
});
const total = ref();
const pageSize = ref(54);
const currentPage = ref(1);
const iconName = ref();
const getIcons = computed(() => {
  const iconFilters = icons.filter(icon => {
    if (iconName.value) {
      return icon.indexOf(iconName.value) >= 0;
    } else {
      return true;
    }
  });
  if (total.value != iconFilters.length) {
    currentPage.value = 1;
    total.value = iconFilters.length;
  }
  return iconFilters.slice((currentPage.value - 1) * pageSize.value, currentPage.value * pageSize.value);
});
const emit = defineEmits(["update:modelValue"]);
const selectedIcon = icon => {
  emit("update:modelValue", icon);
};
</script>

<style scoped lang="scss">
.icon-list {
  display: flex;
  flex-wrap: wrap;
  padding-left: 10px;
  margin-top: 10px;
  .icon-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-items: center;
    width: 10%;
    padding: 5px;
    margin: 0 10px 10px 0;
    cursor: pointer;
    border: 1px solid #cccccc;
    &:hover {
      color: var(--el-color-primary);
      border-color: var(--el-color-primary);
      transition: all 0.2s;
      transform: scaleX(1.1);
    }
  }
  .active {
    color: var(--el-color-primary);
    border-color: var(--el-color-primary);
  }
}
</style>
